package com.basis.config;

import java.util.ArrayList;
import java.util.List;

import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;

@Configuration
public class FastJsonCfg {

	/**
	 * @Description: 使用fastjson解析json对象
	 * @param: @return
	 * @return: HttpMessageConverters
	 * @author: lxd
	 * @date: 2019年11月26日 下午1:44:34
	 */
	@Bean
	public HttpMessageConverters fastJsonHttpMessageConverters() {
		// 1.需要定义一个convert转换消息的对象;
		FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
		// 2:添加fastJson的配置信息;
		FastJsonConfig fastJsonConfig = new FastJsonConfig();
		/**
		 * TODO
		 * 第一个SerializerFeature.PrettyFormat可以省略，毕竟这会造成额外的内存消耗和流量，第二个是用来指定当属性值为null时是否输出：pro:null
		 * SerializerFeature.SkipTransientField
		 */
		SerializerFeature[] serializerFeatures = new SerializerFeature[] {
				// 输出key是包含双引号
//                SerializerFeature.QuoteFieldNames,
				// 是否输出为null的字段,若为null 则显示该字段
//                SerializerFeature.WriteMapNullValue,
				// 数值字段如果为null，则输出为0
//                SerializerFeature.WriteNullNumberAsZero,
				// List字段如果为null,输出为[],而非null
//                SerializerFeature.WriteNullListAsEmpty,
				// 字符类型字段如果为null,输出为"",而非null
				SerializerFeature.WriteNullStringAsEmpty,
				// Boolean字段如果为null,输出为false,而非null
//                SerializerFeature.WriteNullBooleanAsFalse,
				// Date的日期转换器
//                SerializerFeature.WriteDateUseDateFormat,
				// 循环引用
//                SerializerFeature.DisableCircularReferenceDetect,
				SerializerFeature.WriteMapNullValue };
		fastJsonConfig.setSerializerFeatures(serializerFeatures);
		// 3处理中文乱码问题
		List<MediaType> fastMediaTypes = new ArrayList<>();
//        fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
		fastMediaTypes.add(MediaType.APPLICATION_JSON);
		// 4.在convert中添加配置信息.
		fastJsonHttpMessageConverter.setSupportedMediaTypes(fastMediaTypes);
		fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);
		HttpMessageConverter<?> converter = fastJsonHttpMessageConverter;
		return new HttpMessageConverters(converter);
	}
}
